package com.taotao.search.dao;

import com.taotao.common.pojo.SearchItem;
import com.taotao.common.pojo.SearchResult;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 从索引库搜索商品
 * 因为只用solr实现所以省去接口
 */

@Repository
public class SearchDao {

    @Autowired
    private SolrClient solrClient;

    /**
     * 根据查询条件搜索商品结果集
     *
     * @param solrQuery
     * @return
     */
    public SearchResult search(SolrQuery solrQuery) throws Exception {
        QueryResponse response = solrClient.query(solrQuery);
        SolrDocumentList results = response.getResults();
        //高亮
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        SearchResult searchResult = new SearchResult();
        searchResult.setPageCount(results.getNumFound());
        List<SearchItem> itemList = new ArrayList<>();

        for (SolrDocument solrDocument : results) {
            SearchItem item = new SearchItem();
            item.setCategory_name(solrDocument.get("item_category_name").toString());
            item.setId(Long.parseLong(solrDocument.get("id").toString()));
            item.setImage(solrDocument.get("item_image").toString());
            item.setPrice((Long) solrDocument.get("item_price"));
            item.setSell_point(solrDocument.get("item_sell_point").toString());
            //取高亮
            List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
            //判断list是否为空
            String gaoliangstr = "";
            if (list != null && list.size() > 0) {
                //有高亮
                gaoliangstr = list.get(0);
            } else {
                gaoliangstr = solrDocument.get("item_title").toString();
            }

            item.setTitle(gaoliangstr);
            itemList.add(item);
        }

        searchResult.setItemList(itemList);

        return searchResult;
    }
}
